//
//  PitchLocatorViewController.m
//  KG
//
//  Created by Eugene Braginets on 14.03.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "PitchLocatorViewController.h"
#import "AppDelegate.h"
#import "Place.h"
#import "PitchNewItemViewController.h"
#import "bannerView.h"


@implementation PitchLocatorViewController
@synthesize changeMapModeButton = _changeMapModeButton;
@synthesize tableView = _tableView;
@synthesize closeKeyboardButton = _closeKeyboardButton;
@synthesize mySearchBar=_mySearchBar;
@synthesize mapView=_mapView;
@synthesize activityIndicator = _activityIndicator;
@synthesize searchText=_searchText;
@synthesize foundItems=_foundItems;
@synthesize mapMode=_mapMode;
@synthesize bannerViewController=_bannerViewController;
@synthesize index=_index;
@synthesize sortedKeys=_sortedKeys;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        _index=[[NSMutableDictionary alloc] init];
        _foundItems=[[NSMutableArray alloc] init];
        _sortedKeys=[[NSArray alloc] init];
        self.searchText=@"";
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self 
             selector: @selector(loadData)
                 name:kPitchItem object: nil];
        self.mapMode=0;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    NSLog(@"pitch locator memory warning");
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [self.tableView setHidden:NO];
    [self.mapView setHidden:YES];
    
    [self.activityIndicator setHidden:NO];
    [self.activityIndicator startAnimating];
    UISearchBar* searchBar=[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 220, 40)];
    [searchBar setBarStyle:UIBarStyleBlackTranslucent];
    [[searchBar.subviews objectAtIndex:0] removeFromSuperview];
    [searchBar setDelegate:self];
    [searchBar setBackgroundColor:[UIColor clearColor]];
    [searchBar setPlaceholder:@"Show all"];
    
    self.navigationItem.titleView=searchBar;
  
    
    _mySearchBar=searchBar;
    
    UIBarButtonItem *logoutButton = [[UIBarButtonItem alloc] 
                                     initWithTitle:@"Map"                                            
                                     style:UIBarButtonItemStyleBordered
                                     target:self 
                                     action:@selector(ListMap)];
    self.navigationItem.rightBarButtonItem = logoutButton;
    
  
    self.navigationItem.rightBarButtonItem=logoutButton;
    [self.view setBackgroundColor:[UIColor colorWithRed:.3 green:.6 blue:.1 alpha:1]];
    
   	if ([[kPitchesArray objectAtIndex:0]title]){
        [self loadData];
    }
 
    bannerView *bannerVC=[[bannerView alloc] init];
    [self.view addSubview:bannerVC.view];
    [bannerVC animate];
    self.bannerViewController=bannerVC;

       [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setMapView:nil];
    [self setMySearchBar:nil];
    [self setCloseKeyboardButton:nil];
    [self setActivityIndicator:nil];
    [self setTableView:nil];
    [self setChangeMapModeButton:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

#pragma mark - custom methods

- (void) ListMap {

    if (self.tableView.hidden) {
        [self.tableView setHidden:NO];
        [UIView animateWithDuration:0.4 animations:^{
            self.mapView.alpha=0;
        }];
        [self.mapView setHidden:YES];
        [self.changeMapModeButton setHidden:YES];
        self.navigationItem.rightBarButtonItem.title=@"Map";
        
        [self.activityIndicator setHidden:YES];
        [self.tableView reloadData];
        
    } 
    else {
        self.mapView.alpha=0;
         [self putAnnotations];
        [self.mapView setHidden:NO];
        [UIView animateWithDuration:0.4 animations:^{
            self.mapView.alpha=1;
        }];
        [self.tableView setHidden:YES];
        [self.changeMapModeButton setHidden:NO];
       
        self.navigationItem.rightBarButtonItem.title=@"List";
    }
        

}

- (void) doSearch {
    NSLog (@"do search");
//    [self.activityIndicator startAnimating];
//    [self.activityIndicator setHidden:NO];
//    [UIView animateWithDuration:0.4 animations:^{
//        //        self.careerWebView.frame = CGRectMake(0, 10, 315, 350);
//        self.mapView.alpha=0;
//        self.tableView.alpha=0;
//    }];
//    
    
    NSString* text=self.mySearchBar.text;

//    if ([[text substringToIndex:1] isEqualToString:@"\u200B"]) {
//        text=[text substringFromIndex:1];
        
//    }
    self.searchText=text;

    //    NSString* url=[NSString stringWithFormat:@"%@&like=%@", kGetPitchesURL,[myAppDelegate encodeToURLString:text]];
//    [myAppDelegate getData:url andType:kPitchItem];

    [self loadData];
}
- (void) addToIndex:(Place*)k {
    NSString* let=[[k title] substringToIndex:1];
    if ([self.index objectForKey:let]) {
        //                NSLog (@"there is index for %@. I will add %@",let,[k title]);
        [[self.index objectForKey:let] addObject:k];
    } 
    else {
        //                NSLog (@"there is no index for %@. I will create it for  %@",let,[k title]);
        NSMutableArray* ta=[[NSMutableArray alloc] init];
        //                NSLog(@"k object: %@",k);
        [ta addObject:k];
        //                 NSLog(@"ta %@",ta);
        [self.index setObject:ta forKey:let];
        NSLog(@"self.index count %d",[[self.index allKeys] count]);
    }
}

- (void) updateUI {
    [self.activityIndicator stopAnimating];
    [self.activityIndicator setHidden:YES];
    [self.tableView reloadData];
    if ([self.foundItems count]==0) {
        [myAppDelegate msg:@"No pitches found on this criteria"];
    }
    NSLog(@"len=%d",[self.foundItems count]);
    if (!self.mapView.hidden) {
        [self putAnnotations];   
    }

}

- (void) loadData {
    NSLog (@"loadData");
   
    NSMutableDictionary* emptyDict=[[NSMutableDictionary alloc] init ];
    self.index=emptyDict;
    
    
    if (kPitchesArray) {
        [self.foundItems removeAllObjects];
        for (Place* k in kPitchesArray) {
            
//            NSLog (@"Pitch name:%@",k.title);
//            NSLog (@"Pitch keywords:%@",k.keywords);
            
            NSRange textRange;
            NSString* keywords=[NSString stringWithFormat:@"%@%@",k.title,k.keywords];
            
            textRange =[[keywords lowercaseString] rangeOfString:[self.searchText lowercaseString]];
            
            if((textRange.location != NSNotFound) || ([self.searchText isEqualToString:@""])) {
                
//                NSLog(@"%@ i swhat you looking for",[k title]);
                [self.foundItems addObject:k];
           
                                   
                }

//           else NSLog(@"%@ is not you looked for!",[k title]);
            
        }
        
        for (Place* s in self.foundItems) {
//            NSLog(@"%@ added to found",[s title]);
                        [self addToIndex:s];
        }
        NSSortDescriptor *desc = [[NSSortDescriptor alloc] initWithKey:nil ascending:YES selector:@selector(localizedCompare:)]; 
        NSArray *sortedArray = [[self.index allKeys] sortedArrayUsingDescriptors:[NSArray arrayWithObject:desc]];
        
        self.sortedKeys=sortedArray;
        
        [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:NO];
//        NSLog (@"INDEX: %@",self.index);
    }
}


- (IBAction)changeMapMode:(id)sender {
    NSLog(@"change map mode to:%d",self.mapMode);
    switch (self.mapMode) {
        case 0:
            [self.mapView setMapType:MKMapTypeStandard];
            [self.changeMapModeButton setImage:[UIImage imageNamed:[kMapModeButtons objectAtIndex:1]] forState:UIControlStateNormal];
            break;
        case 1:
            [self.mapView setMapType:MKMapTypeSatellite];
            [self.changeMapModeButton setImage:[UIImage imageNamed:[kMapModeButtons objectAtIndex:2]] forState:UIControlStateNormal];

            break;
        case 2:
            [self.mapView setMapType:MKMapTypeHybrid];
            [self.changeMapModeButton setImage:[UIImage imageNamed:[kMapModeButtons objectAtIndex:0]] forState:UIControlStateNormal];

            break;
            
        default:
            [self.mapView setMapType:MKMapTypeStandard];
            [self.changeMapModeButton setImage:[UIImage imageNamed:[kMapModeButtons objectAtIndex:1]] forState:UIControlStateNormal];

            break;
    }
    self.mapMode+=1;
    if (self.mapMode>2) self.mapMode=0; 
}

#pragma mark - SearchBar Delegate methods
- (void)handleSearch:(UISearchBar *)searchBar {
    NSLog(@"User searched for %@", searchBar.text);
    [self doSearch];
    [self.closeKeyboardButton setHidden:YES];
    [searchBar resignFirstResponder]; // if you want the keyboard to go away
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self handleSearch:searchBar];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    
    NSLog(@"Text did end editing %@",searchBar.text);
}



- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar {
    NSLog(@"User canceled search");
    [searchBar resignFirstResponder]; // if you want the keyboard to go away
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSLog(@"text: %@",[myAppDelegate encodeToURLString:searchText]);
    if ([searchText length]==0){
//       self.mySearchBar.text=@"\u200B";
        [searchBar resignFirstResponder];
        [self doSearch];
    }
     
    //    NSLog(@"Text did change %@",searchText);
    
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    [self.closeKeyboardButton setHidden:NO];
//    if ([searchBar.text length]<1){
//        searchBar.text=@"\u200B";
//    }
}

- (void)searchDisplayControllerDidBeginSearch:(UISearchDisplayController*)controller
{
    NSLog(@"Starting search");  
//    controller.searchBar.text = @"\u200B";
}

- (IBAction)closeKeyboard:(id)sender {
    [self.mySearchBar resignFirstResponder];
    [self.closeKeyboardButton setHidden:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - tableView method

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 62;    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [self.sortedKeys count];
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [[self.index objectForKey:[self.sortedKeys objectAtIndex:section]] count];
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView* view;
    UILabel* label;
    view=[[UIView alloc] init];
    CGRect frame=CGRectMake(10, 0, 310, 20);
    label=[[UILabel alloc] initWithFrame:frame];
    
    label.text=[self.sortedKeys objectAtIndex:section];
    
    
    [view setBackgroundColor:[UIColor colorWithRed:.25 green:.3 blue:.05 alpha:1]];

    [label setBackgroundColor:[UIColor clearColor]];
    [label setTextColor:[UIColor whiteColor]];
    [label setFont:[UIFont fontWithName:@"system bold" size:14]];
    //    [label setFont:[UIFont systemFontOfSize:14]];
    [label setMinimumFontSize:9];
    
    [view addSubview:label];
    [view setContentMode:UIViewContentModeTop];
    return view;
}





// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *MyIdentifier = @"MyIdentifier";
    MyIdentifier = @"tblCellView";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:MyIdentifier];
    }
    
	cell.textLabel.text=[[[self.index objectForKey:[self.sortedKeys objectAtIndex:indexPath.section]]  objectAtIndex:indexPath.row] title];
    
//    cell.detailTextLabel.text=[[kNewsArray  objectAtIndex:indexPath.row] publishdate];
    
    [cell.detailTextLabel setTextColor:[UIColor blackColor]];
    
    UIView *bgColorView = [[UIView alloc] init];
    [bgColorView setBackgroundColor:[UIColor colorWithRed:.25 green:.3 blue:.05 alpha:0.7]];

    
    [cell setSelectedBackgroundView:bgColorView];
    
    //[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
    
    [cell setAccessoryView:[self makeDetailDisclosureButton]];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setBackgroundColor:[UIColor clearColor]];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog (@"selected row %d", indexPath.row);
    PitchNewItemViewController* pitchItemViewController=[[PitchNewItemViewController alloc] initWithPlace:[[self.index objectForKey:[self.sortedKeys objectAtIndex:indexPath.section]]  objectAtIndex:indexPath.row]];
    //    
    [self setTitle:@"Back"];
    
    if (pitchItemViewController) {
        pitchItemViewController.navigationItem.title=@"Pitch Description";
        [self.navigationController pushViewController:pitchItemViewController animated:YES];
    }

  
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    NSLog (@"selected accessory from row %d", indexPath.row);
    
    
//    NSString* itemid=[[kNewsArray objectAtIndex:indexPath.row] itemid];
//    NSString*  name=[NSString stringWithFormat:@"%@%@",kNewsItem,itemid];
//    [self loadNewsItem:[kNewsArray objectAtIndex:indexPath.row]];
//    
    PitchNewItemViewController* pitchItemViewController=[[PitchNewItemViewController alloc] initWithPlace:[[self.index objectForKey:[self.sortedKeys objectAtIndex:indexPath.section]]  objectAtIndex:indexPath.row]];
//    
    [self setTitle:@"Back"];
    
    if (pitchItemViewController) {
        pitchItemViewController.navigationItem.title=@"Pitch Description";
        //[[self.foundItems objectAtIndex:indexPath.row] title];
        [self.navigationController pushViewController:pitchItemViewController animated:YES];
    }
}

//helper for accessoryButtonTapped
- (void) accessoryButtonTapped: (UIControl *) button withEvent: (UIEvent *) event
{
    NSIndexPath * indexPath = [self.tableView indexPathForRowAtPoint: [[[event touchesForView: button] anyObject] locationInView: self.tableView]];
    if ( indexPath == nil )
        return;
    [self.tableView.delegate tableView: self.tableView accessoryButtonTappedForRowWithIndexPath: indexPath];
}

- (UIButton *) makeDetailDisclosureButton {
    UIButton * button =[UIButton buttonWithType:UIButtonTypeCustom];
    [button setImage:[UIImage imageNamed:@"rightarrow"] forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor clearColor]];
    [button setFrame:CGRectMake(0, 0, 25, 25)];
    
    [button setImage:[UIImage imageNamed:@"rightarrow"] forState:UIControlStateHighlighted];
    [button setImage:[UIImage imageNamed:@"rightarrow_pressed"] forState:UIControlStateSelected];
    [button setImage:[UIImage imageNamed:@"rightarrow_pressed"] forState:UIControlStateHighlighted];
    
    [button addTarget: self
               action: @selector(accessoryButtonTapped:withEvent:)
     forControlEvents: UIControlEventTouchUpInside];
    
    return ( button );
    
}


#pragma mark - MKMapViewDelegate

-(void)  mapView:(MKMapView *)mapView 
didUpdateUserLocation:(MKUserLocation *)userLocation {
//    NSLog (@"MKMAPVIEW lat: %f",userLocation.location.coordinate.latitude);
//	NSLog (@"MKMAPVIEW lng: %f",userLocation.location.coordinate.longitude);
    //    NSLog (@"from appDelegate latitude: %f",[myAppDelegate location].coordinate.latitude);
    //    NSLog (@"from appDelegate longitude: %f",[myAppDelegate location].coordinate.longitude);
    
}


- (void)mapView:(MKMapView *)mapView_local regionDidChangeAnimated:(BOOL)animated {
//	NSLog (@"Region changed");
//	NSLog (@"MAP lat: %f",mapView_local.region.center.latitude);
//	NSLog (@"MAP lng: %f",mapView_local.region.center.longitude);
//	NSLog (@"size region: %f",mapView_local.region.span.latitudeDelta);
}


- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
	NSLog (@"welcome to annotations!");
	
	// if it's the user location, just return nil.
    if ([annotation isKindOfClass:[MKUserLocation class]])
        return nil;
    
	// try to dequeue an existing pin view first
	static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
	MKPinAnnotationView* pinView = [[MKPinAnnotationView alloc]
								  initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
	pinView.canShowCallout=YES;
	
	UIButton* but=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
	[pinView setRightCalloutAccessoryView:but];
    
	[pinView setAnimatesDrop:NO];
   [pinView setPinColor:MKPinAnnotationColorGreen];
	
//	pinView.image = [UIImage imageNamed:@"map_pin.png"];
//    [pinView setContentScaleFactor:2];
//    pinView.centerOffset = CGPointMake(0, -30);

	return pinView;
	
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control{
	
    PitchNewItemViewController *viewController = [[PitchNewItemViewController alloc] 
          initWithPlace:(Place*)view.annotation];
	[self.navigationController pushViewController:viewController animated:YES];
}





#pragma mark - annotations 

- (void)putAnnotations {
	
    NSLog (@"remove previous annotations");
    
    for (Place* item in self.mapView.annotations) {
        if (![item isKindOfClass:[MKUserLocation class]])
            [self.mapView removeAnnotation:item];
    }
    
    NSLog (@"put new annotations");

	for(Place* place in self.foundItems){
        [self.mapView addAnnotation:place]; 
    }
	//Zoom up to fit all annotations
	//[self zoomToFitMapAnnotations];
	
	//center on user's location and make region
    //	[self gotoLocation];
    
    [self zoomToFitMapAnnotations];
}

- (void) gotoLocation {
    //centring map on user's location
    CLLocationCoordinate2D centerPoint;
    centerPoint=self.mapView.userLocation.location.coordinate;
    MKCoordinateRegion newRegion=MKCoordinateRegionMakeWithDistance (centerPoint, self.mapView.region.span.latitudeDelta, self.mapView.region.span.longitudeDelta);
    [self.mapView setRegion:newRegion animated:YES];
}

- (void)zoomToFitMapAnnotations {
    NSLog(@"zoom to fit annotations");
    int k=0;
    if([self.mapView.annotations count] == 0)
        return;
    if ([self.mapView.annotations count] ==1)
        k=1;
    NSLog (@"count: %d, k:%d",self.mapView.annotations.count,k);
    CLLocationCoordinate2D topLeftCoord;
    topLeftCoord.latitude = -90;
    topLeftCoord.longitude = 180;
    
    CLLocationCoordinate2D bottomRightCoord;
    bottomRightCoord.latitude = 90;
    bottomRightCoord.longitude = -180;
    
    for(Place* annotation in self.mapView.annotations)
    {
        topLeftCoord.longitude = fmin(topLeftCoord.longitude, annotation.coordinate.longitude);
        topLeftCoord.latitude = fmax(topLeftCoord.latitude, annotation.coordinate.latitude);
        
        bottomRightCoord.longitude = fmax(bottomRightCoord.longitude, annotation.coordinate.longitude);
        bottomRightCoord.latitude = fmin(bottomRightCoord.latitude, annotation.coordinate.latitude);
    }
    
    MKCoordinateRegion region;
    region.span.latitudeDelta = fabs(topLeftCoord.latitude - bottomRightCoord.latitude) * 1.5+k; // Add a little extra space on the sides
    region.span.longitudeDelta = fabs(bottomRightCoord.longitude - topLeftCoord.longitude) * 1.5+k; // Add a little extra space on the sides
    
    region.center.latitude = (topLeftCoord.latitude - (topLeftCoord.latitude - bottomRightCoord.latitude) * 0.5)+region.span.latitudeDelta*0.15; //slithly shift center
    region.center.longitude = (topLeftCoord.longitude + (bottomRightCoord.longitude - topLeftCoord.longitude) * 0.5)*1;
    
//    region = [MKMapView regionThatFits:region];
    [self.mapView setRegion:region animated:YES];
    
}






@end
